#
# messkit.token_bucket
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Token Bucket

We use this a little differently from a classical token bucket in that
we allow going into debt.  That is, we proceed with an operation if
the balance is positive, even if we don't know how many tokens it will
require.
"""

import time

class TokenBucket(object):
    def __init__(self, rate, capacity, now=None):
        self.rate = rate
        self.capacity = capacity
        self.balance = capacity
        self.timestamp = now or time.time()

    def authorize(self, amount=0, now=None):
        self._update(now)
        return self.balance > amount

    def debit(self, amount):
        self.balance -= amount

    def _update(self, now=None):
        now = now or time.time()
        elapsed = now - self.timestamp
        self.timestamp = now
        self.balance = min(self.balance + elapsed * self.rate, self.capacity)

if __name__ == '__main__':
    bucket = TokenBucket(100, 500, now=10.0)

    assert bucket.authorize(now=11.0)
    assert bucket.authorize(499, now=12.0)
    assert not bucket.authorize(501, now=13.0)
    assert bucket.balance == 500

    bucket.debit(400)
    assert bucket.balance == 100

    bucket.debit(200)
    assert bucket.balance == -100

    assert not bucket.authorize(now=13.5)
    assert bucket.balance == -50

    assert bucket.authorize(now=16.0)
    assert bucket.balance == 200

    assert bucket.authorize(now=30.0)
    assert bucket.balance == 500

    print 'OK'
